package iscas;

public class RedisBarrier {
    private static volatile boolean barrier;
    private static final Object wait = new Object();

    static {
        RedisConfig.subscribe((String msg) -> {
            if (msg.equals("true")) {
                barrier = true;
            } else if (msg.equals("false")) {
                barrier = false;
                synchronized (wait) {
                    wait.notifyAll();
                }
            }
        }, "barrierChannel");
    }

    public static boolean isBarrier() {
        return barrier;
    }

    public static void barrier() {
        if (barrier) {
            System.out.printf("[ISCAS][barrier] %s wait\n", Thread.currentThread().getName());
            synchronized (wait) {
                try {
                    wait.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.printf("[ISCAS][barrier] %s notify\n", Thread.currentThread().getName());
        }
    }
}
